package com.adams.app.ui.fragment;

import java.util.ArrayList;

import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.adams.app.R;
import com.adams.app.dao.SpecialtyDateHelper;
import com.adams.app.data.GsonRequest;
import com.adams.app.model.Specialty;
import com.adams.app.ui.MainActivity;
import com.adams.app.ui.ScrollViewActivity;
import com.adams.app.ui.adapter.CardsAnimationAdapter;
import com.adams.app.ui.adapter.SpecialtyAdapter;
import com.adams.app.utils.CommonUtils;
import com.adams.app.vendor.HappyGyApi;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.haarman.listviewanimations.swinginadapters.AnimationAdapter;

/**
 * Created by Adams on 13-12-27.
 */
public class SpecialtyFragment extends BaseFragment implements
		LoaderManager.LoaderCallbacks<Cursor>,
		PullToRefreshAttacher.OnRefreshListener {

	private ListView mListView;
	private SpecialtyDateHelper mDataHelper;
	private SpecialtyAdapter mAdapter;
	private PullToRefreshAttacher mPullToRefreshAttacher;

	public SpecialtyFragment() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View contentView = inflater
				.inflate(R.layout.fragment_attractions, null);
		mListView = (ListView) contentView.findViewById(R.id.listView);

		// 数据库
		mDataHelper = new SpecialtyDateHelper(getActivity());
		mAdapter = new SpecialtyAdapter(getActivity(), mListView);

		View header = new View(getActivity());

		// 下拉刷新
		mPullToRefreshAttacher = ((MainActivity) getActivity())
				.getPullToRefreshAttacher();
		mPullToRefreshAttacher.setRefreshableView(mListView, this);

		// listView添加控件
		mListView.addHeaderView(header);

		// 动画适配器
		AnimationAdapter animationAdapter = new CardsAnimationAdapter(mAdapter);
		animationAdapter.setListView(mListView);
		mListView.setAdapter(animationAdapter);

		// 准备装载器
		getLoaderManager().initLoader(0, null, this);

		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Specialty specialty = mAdapter.getItem(position - mListView.getHeaderViewsCount());
				Intent intent = new Intent(getActivity(), ScrollViewActivity.class);
				intent.putExtra("title", specialty.getName());
				intent.putExtra("url", specialty.getPicture());
				intent.putExtra("context", specialty.getIntro());
				getActivity().startActivity(intent);
			}
		});

		return contentView;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mPullToRefreshAttacher.getHeaderTransformer().onConfigurationChanged(
				getActivity());
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	// 加载数据
	private void loadData() {
		final boolean isRefreshFromTop = true;
		if (!mPullToRefreshAttacher.isRefreshing()) {
			mPullToRefreshAttacher.setRefreshing(true);
		}
		executeRequest(new GsonRequest<Specialty.SpecialtyRequestData>(
				String.format(HappyGyApi.SPECIALTY_LIST, 1),
				Specialty.SpecialtyRequestData.class, null,
				new Response.Listener<Specialty.SpecialtyRequestData>() {
					@Override
					public void onResponse(
							final Specialty.SpecialtyRequestData requestData) {
						CommonUtils
								.executeAsyncTask(new AsyncTask<Object, Object, Object>() {
									@Override
									protected Object doInBackground(
											Object... params) {
										if (requestData.getSpecialty().size() > 0) {
											ArrayList<Specialty> specialties = requestData
													.getSpecialty();
											mDataHelper.deleteAll();
											mDataHelper.bulkInsert(specialties);
										}
										return null;
									}

									@Override
									protected void onPostExecute(Object o) {
										super.onPostExecute(o);
										if (isRefreshFromTop) {
											mPullToRefreshAttacher
													.setRefreshComplete();
										}
									}
								});
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						Toast.makeText(getActivity(),
								R.string.refresh_list_failed,
								Toast.LENGTH_SHORT).show();
						if (isRefreshFromTop) {
							mPullToRefreshAttacher.setRefreshComplete();
						}
					}
				}));
	}

	// //////////////////////////
	//
	// LoaderCallbacks
	//
	// /////////////////////////
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return mDataHelper.getCursorLoader();
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		mAdapter.changeCursor(data);
		if (data != null && data.getCount() == 0) {
			loadData();
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mAdapter.changeCursor(null);
	}

	// //////////////////////////
	//
	// OnRefreshListener
	//
	// /////////////////////////
	@Override
	public void onRefreshStarted(View view) {
		loadData();
	}

}
